<template>
  <Editor v-model="content" :init="myTinyInit"></Editor>
</template>

<script setup>
import {
  computed,
  defineEmits,
  defineProps,
  onMounted,
  reactive,
  ref,
  watch,
} from "vue";
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/icons/default/icons";
import "tinymce/themes/silver";
import "tinymce/models/dom/model";

//按需引入插件
import "tinymce/plugins/image";
import "tinymce/plugins/table";
import "tinymce/plugins/lists";
import "tinymce/plugins/link";
import "tinymce/plugins/save";
import "tinymce/plugins/wordcount";
import "tinymce/plugins/codesample";

// import axios from "axios";
// import { useStore } from "vuex";
// import { ElNotification } from "element-plus";

const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  },
  plugins: {
    type: [String, Array],
    default: "lists link image table help wordcount codesample save",
  },
  toolbar: {
    type: [String, Array],
    default:
      "undo redo | formatselect | bold italic forecolor backcolor | codesample | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | table image | save",
  },
});
const emit = defineEmits(["input"]);

// const store = useStore();
const myTinyInit = reactive({
  width: "100%",
  height: "100%",
  branding: false,
  menubar: false,
  resize: false,
  skin_url: "/tinymce/skins/ui/oxide", //手动引入
  content_css: "/tinymce/skins/content/default/content.css", //手动引入
  toolbar_mode: "wrap",
  plugins: props.plugins,
  toolbar: props.toolbar,
  codesample_content_css: "/static/prism.css",
  save_onsavecallback: function () {
    tipsJS("已保存");
  },
  //图片上传方法（注意！！：要使用 promise 对象中的 resolve 返回图片路径，否则会报错）
  images_upload_handler: (blobInfo) =>
    new Promise((resolve, reject) => {
      let formData = new FormData();
      formData.append("file", blobInfo.blob(), blobInfo.filename());
      // axios
      //   .post(`/api/backend/upload`, formData, {
      //     // headers: {
      //     //   "Content-Type": "multipart/form-data",
      //     //   Authorization: "Bearer " + store.state.user.accessToken,
      //     // },
      //   })
      //   .then((res) => {
      //     if (res.data.code === 1) {
      //       resolve(`/image_manipulation${res.data.data.filePath}`);
      //     } else {
      //       // ElNotification.warning(res.data.msg);
      //     }
      //   })
      //   .catch((error) => {
      //     reject(error);
      //   });
    }),
});

const initContent = computed(() => {
  return props.modelValue;
});

onMounted(() => {
  tinymce.init({});
});

const content = ref();
watch(
  initContent,
  (newVal) => {
    content.value = newVal;
  },
  { deep: true, immediate: true }
);

watch(
  content,
  (newVal) => {
    emit("input", newVal);
  },
  { deep: true }
);
</script>

<style scoped lang="scss"></style>
